#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
#include <libavutil/imgutils.h>
#include <libavutil/avutil.h>
#include <libavutil/display.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <signal.h>
#include <limits.h>
#include <ctype.h>
#include <locale.h>

#define MAX_VIDEO_FILES 100
#define VIDEO_DIR "/视频"  // 相对于用户主目录
#define SEEK_STEP 5000    // 快进快退步长(毫秒)
#define MIN_SEEK_INTERVAL 300 // 最小寻址间隔(毫秒)

// 全局变量用于信号处理
volatile sig_atomic_t quit_flag = 0;

typedef struct {
    AVFormatContext *pFormatCtx;
    AVCodecContext *videoCodecCtx;
    AVCodecContext *audioCodecCtx;
    struct SwsContext *sws_ctx;
    struct SwrContext *swr_ctx;
    int videoStream;
    int audioStream;
    SDL_Window *window;
    SDL_Renderer *renderer;
    SDL_Texture *texture;
    SDL_AudioDeviceID audioDevice;
    int rotation; // 视频旋转角度
    int original_width, original_height; // 视频原始宽高
    int display_width, display_height; // 显示宽高（考虑旋转后）
    int paused; // 暂停状态标志
    int seek_time; // 需要跳转的时间(毫秒)
    Uint32 last_seek_time; // 上次跳转时间
} PlayerState;

typedef struct {
    char filenames[MAX_VIDEO_FILES][PATH_MAX]; // 使用PATH_MAX作为路径长度
    int count;
    int current;
} VideoList;

// 信号处理函数
void handle_signal(int sig) {
    (void)sig; // 显式忽略参数
    quit_flag = 1;
}

// 获取用户主目录
char* get_home_dir() {
    struct passwd *pw = getpwuid(getuid());
    return pw ? pw->pw_dir : NULL;
}

// 获取文件基本名（不含路径和后缀）
void get_basename(const char *filename, char *basename) {
    const char *base = strrchr(filename, '/');
    if (!base) base = filename;
    else base++;
    
    const char *dot = strrchr(base, '.');
    if (dot) {
        size_t base_len = dot - base;
        if (base_len >= PATH_MAX) base_len = PATH_MAX - 1;
        memcpy(basename, base, base_len);
        basename[base_len] = '\0';
    } else {
        strncpy(basename, base, PATH_MAX - 1);
        basename[PATH_MAX - 1] = '\0';
    }
}

// 重命名文件
int rename_file(const char *old_path, const char *new_name) {
    char new_path[PATH_MAX];
    const char *slash = strrchr(old_path, '/');
    
    if (!slash) {
        size_t new_name_len = strlen(new_name);
        if (new_name_len >= PATH_MAX) new_name_len = PATH_MAX - 1;
        memcpy(new_path, new_name, new_name_len);
        new_path[new_name_len] = '\0';
    } else {
        size_t dir_len = slash - old_path + 1;
        size_t dir_len_cpy = dir_len < PATH_MAX ? dir_len : PATH_MAX - 1;
        memcpy(new_path, old_path, dir_len_cpy);
        new_path[dir_len_cpy] = '\0';
        strncat(new_path, new_name, PATH_MAX - strlen(new_path) - 1);
    }
    
    // 检查新文件名是否已存在
    if (access(new_path, F_OK) == 0) {
        fprintf(stderr, "错误: 文件 %s 已存在\n", new_path);
        return -1;
    }
    
    if (rename(old_path, new_path)) {
        perror("重命名失败");
        return -1;
    }
    
    return 0;
}

// 删除文件
int delete_file(const char *filename) {
    if (unlink(filename) != 0) {
        perror("删除文件失败");
        return -1;
    }
    return 0;
}

int get_video_files(VideoList *video_list) {
    if (!video_list) return -1;

    char dir_path[PATH_MAX];
    const char *home_dir = get_home_dir();
    if (!home_dir) {
        fprintf(stderr, "无法获取用户主目录\n");
        return -1;
    }

    if (snprintf(dir_path, sizeof(dir_path), "%s%s", home_dir, VIDEO_DIR) >= (int)sizeof(dir_path)) {
        fprintf(stderr, "路径过长被截断: %s%s\n", home_dir, VIDEO_DIR);
        return -1;
    }
    
    DIR *dir = opendir(dir_path);
    if (!dir) {
        fprintf(stderr, "无法打开目录: %s\n", dir_path);
        return -1;
    }
    
    video_list->count = 0;
    struct dirent *entry;
    
    while ((entry = readdir(dir))) {
        if (video_list->count >= MAX_VIDEO_FILES) break;

        char full_path[PATH_MAX];
        if (snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, entry->d_name) >= (int)sizeof(full_path)) {
            fprintf(stderr, "路径过长被截断: %s/%s\n", dir_path, entry->d_name);
            continue;
        }
        
        struct stat statbuf;
        if (stat(full_path, &statbuf) == -1) {
            continue;
        }
        
        if (S_ISREG(statbuf.st_mode)) {
            const char *ext = strrchr(entry->d_name, '.');
            if (ext) {
                if (strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mkv") == 0 || 
                    strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".mov") == 0 ||
                    strcasecmp(ext, ".flv") == 0 || strcasecmp(ext, ".wmv") == 0) {
                    
                    size_t fp_len = strlen(full_path);
                    if (fp_len >= PATH_MAX) fp_len = PATH_MAX - 1;
                    memcpy(video_list->filenames[video_list->count], full_path, fp_len);
                    video_list->filenames[video_list->count][fp_len] = '\0';
                    video_list->count++;
                }
            }
        }
    }
    
    closedir(dir);
    
    // 按文件名排序，使播放顺序更合理
    qsort(video_list->filenames, video_list->count, sizeof(video_list->filenames[0]), 
        (int (*)(const void*, const void*))strcasecmp);
    
    return video_list->count > 0 ? 0 : -1;
}

void cleanup_player(PlayerState *s) {
    if (s->sws_ctx) {
        sws_freeContext(s->sws_ctx);
        s->sws_ctx = NULL;
    }
    if (s->swr_ctx) {
        swr_free(&s->swr_ctx);
        s->swr_ctx = NULL;
    }
    if (s->texture) {
        SDL_DestroyTexture(s->texture);
        s->texture = NULL;
    }
    if (s->audioDevice) {
        SDL_ClearQueuedAudio(s->audioDevice);
        SDL_CloseAudioDevice(s->audioDevice);
        s->audioDevice = 0;
    }
    if (s->videoCodecCtx) {
        avcodec_free_context(&s->videoCodecCtx);
        s->videoCodecCtx = NULL;
    }
    if (s->audioCodecCtx) {
        avcodec_free_context(&s->audioCodecCtx);
        s->audioCodecCtx = NULL;
    }
    if (s->pFormatCtx) {
        avformat_close_input(&s->pFormatCtx);
        s->pFormatCtx = NULL;
    }
}

// 获取视频旋转角度
int get_video_rotation(AVStream *videoStream) {
    AVDictionaryEntry *rotate = av_dict_get(videoStream->metadata, "rotate", NULL, 0);
    if (rotate && rotate->value) {
        return atoi(rotate->value);
    }
    return 0;
}

// 初始化SDL窗口和渲染器
int init_sdl(PlayerState *s) {
    if (s->window && s->renderer) {
        return 0; // 已经初始化
    }

    SDL_DisplayMode dm;
    if (SDL_GetDesktopDisplayMode(0, &dm) != 0) {
        fprintf(stderr, "无法获取显示模式: %s\n", SDL_GetError());
        return -1;
    }
    
    // 先尝试创建加速渲染器
    s->window = SDL_CreateWindow("视频播放器", 
        SDL_WINDOWPOS_CENTERED, 
        SDL_WINDOWPOS_CENTERED,
        dm.w, dm.h,
        SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_HIDDEN); // 初始隐藏窗口
    
    if (!s->window) {
        fprintf(stderr, "无法创建窗口: %s\n", SDL_GetError());
        return -1;
    }
    
    s->renderer = SDL_CreateRenderer(s->window, -1, 
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    
    // 如果加速渲染器失败，尝试软件渲染
    if (!s->renderer) {
        fprintf(stderr, "无法创建加速渲染器，尝试软件渲染: %s\n", SDL_GetError());
        s->renderer = SDL_CreateRenderer(s->window, -1, SDL_RENDERER_SOFTWARE);
        if (!s->renderer) {
            fprintf(stderr, "无法创建渲染器: %s\n", SDL_GetError());
            return -1;
        }
    }
    
    // 设置渲染器混合模式
    SDL_SetRenderDrawBlendMode(s->renderer, SDL_BLENDMODE_BLEND);
    return 0;
}

int init_player(PlayerState *s, const char *filename) {
    // 清理之前的资源（保留窗口和渲染器）
    cleanup_player(s);
    
    // 初始化SDL窗口和渲染器（如果尚未初始化）
    if (init_sdl(s) < 0) {
        return -1;
    }
    
    // 打开视频文件
    if (avformat_open_input(&s->pFormatCtx, filename, NULL, NULL) != 0) {
        fprintf(stderr, "无法打开文件: %s\n", filename);
        return -1;
    }
    
    if (avformat_find_stream_info(s->pFormatCtx, NULL) < 0) {
        fprintf(stderr, "无法获取流信息\n");
        return -1;
    }

    // 查找视频和音频流
    s->videoStream = -1;
    s->audioStream = -1;
    for (unsigned int i = 0; i < s->pFormatCtx->nb_streams; i++) {
        enum AVMediaType type = s->pFormatCtx->streams[i]->codecpar->codec_type;
        if (type == AVMEDIA_TYPE_VIDEO && s->videoStream == -1) {
            s->videoStream = i;
        } else if (type == AVMEDIA_TYPE_AUDIO && s->audioStream == -1) {
            s->audioStream = i;
        }
    }
    
    if (s->videoStream == -1 && s->audioStream == -1) {
        fprintf(stderr, "文件中没有找到视频或音频流\n");
        return -1;
    }
    
    // 初始化视频
    if (s->videoStream != -1) {
        AVStream *videoStream = s->pFormatCtx->streams[s->videoStream];
        const AVCodec *codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
        if (!codec) {
            fprintf(stderr, "找不到视频编解码器\n");
            return -1;
        }
        
        s->videoCodecCtx = avcodec_alloc_context3(codec);
        if (!s->videoCodecCtx) {
            fprintf(stderr, "无法分配视频编解码器上下文\n");
            return -1;
        }
        
        if (avcodec_parameters_to_context(s->videoCodecCtx, videoStream->codecpar) < 0) {
            fprintf(stderr, "无法复制视频编解码器参数\n");
            return -1;
        }
        
        if (avcodec_open2(s->videoCodecCtx, codec, NULL) < 0) {
            fprintf(stderr, "无法打开视频编解码器\n");
            return -1;
        }

        // 获取视频旋转角度
        s->rotation = get_video_rotation(videoStream);
        
        // 保存原始宽高
        s->original_width = videoStream->codecpar->width;
        s->original_height = videoStream->codecpar->height;
        
        // 确定显示宽高（考虑旋转）
        if (s->rotation == 90 || s->rotation == 270) {
            s->display_width = s->original_height;
            s->display_height = s->original_width;
        } else {
            s->display_width = s->original_width;
            s->display_height = s->original_height;
        }
        
        // 创建纹理
        s->texture = SDL_CreateTexture(s->renderer,
            SDL_PIXELFORMAT_YV12,
            SDL_TEXTUREACCESS_STREAMING,
            s->display_width, s->display_height);
        
        if (!s->texture) {
            fprintf(stderr, "无法创建纹理: %s\n", SDL_GetError());
            return -1;
        }
        
        // 初始化图像转换上下文
        s->sws_ctx = sws_getContext(
            s->original_width,
            s->original_height,
            s->videoCodecCtx->pix_fmt,
            s->display_width, s->display_height,
            AV_PIX_FMT_YUV420P,
            SWS_BILINEAR,
            NULL, NULL, NULL);
        
        if (!s->sws_ctx) {
            fprintf(stderr, "无法初始化图像转换上下文\n");
            return -1;
        }
    }
    
    // 初始化音频
    if (s->audioStream != -1) {
        AVStream *audioStream = s->pFormatCtx->streams[s->audioStream];
        const AVCodec *codec = avcodec_find_decoder(audioStream->codecpar->codec_id);
        if (!codec) {
            fprintf(stderr, "找不到音频编解码器\n");
            return -1;
        }
        
        s->audioCodecCtx = avcodec_alloc_context3(codec);
        if (!s->audioCodecCtx) {
            fprintf(stderr, "无法分配音频编解码器上下文\n");
            return -1;
        }
        
        if (avcodec_parameters_to_context(s->audioCodecCtx, audioStream->codecpar) < 0) {
            fprintf(stderr, "无法复制音频编解码器参数\n");
            return -1;
        }
        
        if (avcodec_open2(s->audioCodecCtx, codec, NULL) < 0) {
            fprintf(stderr, "无法打开音频编解码器\n");
            return -1;
        }

        SDL_AudioSpec wanted_spec = {
            .freq = audioStream->codecpar->sample_rate,
            .format = AUDIO_S16SYS,
            .channels = audioStream->codecpar->ch_layout.nb_channels,
            .samples = 1024,
            .callback = NULL,
            .userdata = NULL,
            .silence = 0
        };
        
        s->audioDevice = SDL_OpenAudioDevice(NULL, 0, &wanted_spec, NULL, 0);
        if (s->audioDevice == 0) {
            fprintf(stderr, "无法打开音频设备: %s\n", SDL_GetError());
            return -1;
        }
        
        swr_alloc_set_opts2(&s->swr_ctx,
            &audioStream->codecpar->ch_layout,
            AV_SAMPLE_FMT_S16,
            wanted_spec.freq,
            &audioStream->codecpar->ch_layout,
            s->audioCodecCtx->sample_fmt,
            s->audioCodecCtx->sample_rate,
            0, NULL);
        
        if (!s->swr_ctx || swr_init(s->swr_ctx) < 0) {
            fprintf(stderr, "无法初始化音频重采样器\n");
            return -1;
        }
        
        SDL_PauseAudioDevice(s->audioDevice, 0);
    }
    
    // 初始化暂停状态和跳转状态
    s->paused = 0;
    s->seek_time = -1;
    s->last_seek_time = 0;
    
    // 显示窗口（避免初始化时闪烁）
    SDL_ShowWindow(s->window);
    return 0;
}

void render_video_frame(PlayerState *s, AVFrame *frame) {
    // 分配目标图像缓冲区
    uint8_t *dst_data[4] = {NULL};
    int dst_linesize[4] = {0};
    
    if (av_image_alloc(dst_data, dst_linesize,
        s->display_width, s->display_height,
        AV_PIX_FMT_YUV420P, 1) < 0) {
        fprintf(stderr, "无法分配图像缓冲区\n");
        return;
    }
    int y_size = s->display_width * s->display_height;
    int uv_size = y_size / 4;
    memset(dst_data[0], 0, y_size);     // Y平面
    memset(dst_data[1], 128, uv_size);  // U平面（128对应中性色）
    memset(dst_data[2], 128, uv_size);  // V平面
    
    // 转换图像格式
    const uint8_t *const *src_data = (const uint8_t *const *)frame->data;
    sws_scale(s->sws_ctx,
        src_data,
        frame->linesize,
        0,
        frame->height,
        dst_data,
        dst_linesize);
    
    // 更新纹理
    SDL_UpdateYUVTexture(s->texture, NULL,
        dst_data[0], dst_linesize[0],
        dst_data[1], dst_linesize[1],
        dst_data[2], dst_linesize[2]);
    
    // 清除渲染器
    SDL_SetRenderDrawColor(s->renderer, 0, 0, 0, 255);
    SDL_RenderClear(s->renderer);
    
    // 计算自适应缩放后的显示区域
    SDL_Rect rect;
    int window_w, window_h;
    SDL_GetWindowSize(s->window, &window_w, &window_h);
    
    float video_aspect = (float)s->display_width / s->display_height;
    float window_aspect = (float)window_w / window_h;
    
    if (video_aspect > window_aspect) {
        // 以宽度为准
        rect.w = window_w;
        rect.h = (int)(window_w / video_aspect);
        rect.x = 0;
        rect.y = (window_h - rect.h) / 2;
    } else {
        // 以高度为准
        rect.h = window_h;
        rect.w = (int)(window_h * video_aspect);
        rect.x = (window_w - rect.w) / 2;
        rect.y = 0;
    }
    
    // 应用旋转
    if (s->rotation != 0) {
        SDL_Point center = {rect.w / 2, rect.h / 2};
        SDL_RenderCopyEx(s->renderer, s->texture, NULL, &rect, s->rotation, &center, SDL_FLIP_NONE);
    } else {
        SDL_RenderCopy(s->renderer, s->texture, NULL, &rect);
    }
    
    // 如果处于暂停状态，显示暂停图标
    if (s->paused) {
        SDL_SetRenderDrawColor(s->renderer, 255, 255, 255, 180);
        SDL_Rect pause_rect1 = {window_w/2 - 30, window_h/2 - 30, 20, 60};
        SDL_Rect pause_rect2 = {window_w/2 + 10, window_h/2 - 30, 20, 60};
        SDL_RenderFillRect(s->renderer, &pause_rect1);
        SDL_RenderFillRect(s->renderer, &pause_rect2);
    }
    
    // 呈现渲染结果
    SDL_RenderPresent(s->renderer);
    
    // 释放图像缓冲区
    av_freep(&dst_data[0]);
}

// 显示文本输入框并获取输入
int show_text_input_dialog(const char *title, const char *default_text, char *buffer, size_t buffer_size) {
    if (TTF_Init() == -1) {
        fprintf(stderr, "TTF初始化失败: %s\n", TTF_GetError());
        return 0;
    }

  

    // 尝试加载多种字体以兼容不同系统
    const char *font_paths[] = {
        "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", // Ubuntu常见路径
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",         // 文泉驿微米黑
        "/usr/share/fonts/truetype/freefont/FreeSans.ttf",       // FreeSans
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",       // DejaVu Sans
        NULL
    };

    TTF_Font *font = NULL;
    for (int i = 0; font_paths[i] != NULL; i++) {
        font = TTF_OpenFont(font_paths[i], 24);
        if (font) break;
    }

    if (!font) {
        fprintf(stderr, "无法加载字体\n");
        TTF_Quit();
        return 0;
    }

    SDL_Window *input_window = SDL_CreateWindow(title,
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        400, 150, SDL_WINDOW_SHOWN);
    
    if (!input_window) {
        fprintf(stderr, "无法创建输入窗口: %s\n", SDL_GetError());
        TTF_CloseFont(font);
        TTF_Quit();
        return 0;
    }
    
    SDL_Renderer *renderer = SDL_CreateRenderer(input_window, -1, SDL_RENDERER_ACCELERATED);
    if (!renderer) {
        SDL_DestroyWindow(input_window);
        TTF_CloseFont(font);
        TTF_Quit();
        fprintf(stderr, "无法创建渲染器: %s\n", SDL_GetError());
        return 0;
    }

    SDL_StartTextInput();
    
    strncpy(buffer, default_text, buffer_size - 1);
    buffer[buffer_size - 1] = '\0';
    int cursor_pos = strlen(buffer);
    int done = 0;
    int result = 0;
    Uint32 cursor_blink_time = SDL_GetTicks();
    int show_cursor = 1;
    
    while (!done && !quit_flag) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    done = 1;
                    break;
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym) {
                        case SDLK_RETURN:
                            done = 1;
                            result = 1;
                            break;
                        case SDLK_ESCAPE:
                            done = 1;
                            break;
                        case SDLK_BACKSPACE:
                            if (cursor_pos > 0) {
                                // 处理UTF-8字符的退格
                                int bytes_to_remove = 1;
                                while (cursor_pos > bytes_to_remove && 
                                      (buffer[cursor_pos - bytes_to_remove] & 0xC0) == 0x80) {
                                    bytes_to_remove++;
                                }
                                memmove(&buffer[cursor_pos - bytes_to_remove], 
                                       &buffer[cursor_pos], 
                                       strlen(buffer) - cursor_pos + 1);
                                cursor_pos -= bytes_to_remove;
                            }
                            break;
                        case SDLK_DELETE:
                            if (cursor_pos < (int)strlen(buffer)) {
                                // 处理UTF-8字符的删除
                                int bytes_to_remove = 1;
                                while (cursor_pos + bytes_to_remove < (int)strlen(buffer) && 
                                      (buffer[cursor_pos + bytes_to_remove] & 0xC0) == 0x80) {
                                    bytes_to_remove++;
                                }
                                memmove(&buffer[cursor_pos], 
                                       &buffer[cursor_pos + bytes_to_remove], 
                                       strlen(buffer) - cursor_pos - bytes_to_remove + 1);
                            }
                            break;
                        case SDLK_LEFT:
                            if (cursor_pos > 0) {
                                // 处理UTF-8字符的左移
                                do {
                                    cursor_pos--;
                                } while (cursor_pos > 0 && (buffer[cursor_pos] & 0xC0) == 0x80);
                            }
                            break;
                        case SDLK_RIGHT:
                            if (cursor_pos < (int)strlen(buffer)) {
                                // 处理UTF-8字符的右移
                                do {
                                    cursor_pos++;
                                } while (cursor_pos < (int)strlen(buffer) && (buffer[cursor_pos] & 0xC0) == 0x80);
                            }
                            break;
                        case SDLK_HOME:
                            cursor_pos = 0;
                            break;
                        case SDLK_END:
                            cursor_pos = strlen(buffer);
                            break;
                    }
                    break;
                case SDL_TEXTINPUT:
                    // 处理中文输入，直接追加文本而不是逐个字符处理
                    if ((strlen(buffer) + strlen(event.text.text)) < (buffer_size - 1)) {
                        memmove(&buffer[cursor_pos + strlen(event.text.text)], 
                               &buffer[cursor_pos], 
                               strlen(buffer) - cursor_pos + 1);
                        memcpy(&buffer[cursor_pos], event.text.text, strlen(event.text.text));
                        cursor_pos += strlen(event.text.text);
                    }
                    break;
            }
        }

        // 光标闪烁
        if (SDL_GetTicks() - cursor_blink_time > 500) {
            show_cursor = !show_cursor;
            cursor_blink_time = SDL_GetTicks();
        }
        
        // 渲染输入框
        SDL_SetRenderDrawColor(renderer, 240, 240, 240, 255);
        SDL_RenderClear(renderer);
        
        // 绘制输入框边框
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
        SDL_Rect input_rect = {20, 50, 360, 40};
        SDL_RenderDrawRect(renderer, &input_rect);
        
        // 绘制提示文字
        SDL_Color text_color = {0, 0, 0, 255};
        SDL_Surface *prompt_surface = TTF_RenderUTF8_Blended(font, "输入新文件名:", text_color);
        if (prompt_surface) {
            SDL_Texture *prompt_texture = SDL_CreateTextureFromSurface(renderer, prompt_surface);
            if (prompt_texture) {
                SDL_Rect prompt_rect = {20, 10, prompt_surface->w, prompt_surface->h};
                SDL_RenderCopy(renderer, prompt_texture, NULL, &prompt_rect);
                SDL_DestroyTexture(prompt_texture);
            }
            SDL_FreeSurface(prompt_surface);
        }
        
        // 绘制文本内容
        if (strlen(buffer) > 0) {
            SDL_Surface *text_surface = TTF_RenderUTF8_Blended(font, buffer, text_color);
            if (text_surface) {
                SDL_Texture *text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
                if (text_texture) {
                    SDL_Rect text_rect = {25, 55, text_surface->w, text_surface->h};
                    SDL_RenderCopy(renderer, text_texture, NULL, &text_rect);
                    SDL_DestroyTexture(text_texture);
                }
                SDL_FreeSurface(text_surface);
            }
        }
        
        // 绘制光标
        if (show_cursor) {
            int text_width = 0;
            if (strlen(buffer) > 0 && cursor_pos > 0) {
                char temp[PATH_MAX] = {0};
                size_t copy_len = (size_t)cursor_pos < sizeof(temp) - 1 ? (size_t)cursor_pos : sizeof(temp) - 1;
                strncpy(temp, buffer, copy_len);
                temp[copy_len] = '\0';
                TTF_SizeUTF8(font, temp, &text_width, NULL);
            }
            SDL_Rect cursor_rect = {25 + text_width, 55, 2, 30};
            SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
            SDL_RenderFillRect(renderer, &cursor_rect);
        }
        
        SDL_RenderPresent(renderer);
        SDL_Delay(10);
    }
    
    SDL_StopTextInput();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(input_window);
    TTF_CloseFont(font);
    TTF_Quit();
    
    return result;
}

int play_video(PlayerState *s, VideoList *video_list) {
    AVPacket *packet = av_packet_alloc();
    AVFrame *frame = av_frame_alloc();
    if (!packet || !frame) {
        fprintf(stderr, "无法分配数据包或帧\n");
        return -1;
    }
    
    int quit = 0;
    int need_switch = 0;
    int need_reinit = 0;
    
    // 初始渲染一帧黑色背景，避免闪烁
    SDL_SetRenderDrawColor(s->renderer, 0, 0, 0, 255);
    SDL_RenderClear(s->renderer);
    SDL_RenderPresent(s->renderer);
    
    while (!quit_flag && !quit && !need_switch && !need_reinit && av_read_frame(s->pFormatCtx, packet) >= 0) {
        // 处理跳转请求
        if (s->seek_time >= 0) {
            int64_t seek_target = av_rescale(s->seek_time, AV_TIME_BASE, 1000);
            if (av_seek_frame(s->pFormatCtx, -1, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
                fprintf(stderr, "跳转失败\n");
            } else {
                // 清空解码器缓冲区
                if (s->videoCodecCtx) {
                    avcodec_flush_buffers(s->videoCodecCtx);
                }
                if (s->audioCodecCtx) {
                    avcodec_flush_buffers(s->audioCodecCtx);
                }
                // 清空音频队列
                if (s->audioDevice) {
                    SDL_ClearQueuedAudio(s->audioDevice);
                }
            }
            s->seek_time = -1;
            s->last_seek_time = SDL_GetTicks();
            av_packet_unref(packet);
            continue;
        }
        
        if (packet->stream_index == s->videoStream) {
            if (avcodec_send_packet(s->videoCodecCtx, packet) < 0) {
                fprintf(stderr, "发送视频数据包失败\n");
                av_packet_unref(packet);
                continue;
            }
            
            while (!quit_flag && !quit && !need_switch && !need_reinit && avcodec_receive_frame(s->videoCodecCtx, frame) == 0) {
                render_video_frame(s, frame);
                
                // 计算帧延迟
                double frame_rate = av_q2d(av_guess_frame_rate(s->pFormatCtx, 
                    s->pFormatCtx->streams[s->videoStream], NULL));
                if (frame_rate > 0 && !s->paused) {
                    SDL_Delay((Uint32)(1000 / frame_rate));
                }
                
                // 处理事件
                SDL_Event event;
                while (SDL_PollEvent(&event)) {
                    if (event.type == SDL_QUIT) {
                        quit = 1;
                        break;
                    } else if (event.type == SDL_KEYDOWN) {
                        // 检查Ctrl键是否按下
                        int ctrl_pressed = (event.key.keysym.mod & KMOD_CTRL) ? 1 : 0;
                        
                        switch (event.key.keysym.sym) {
                            case SDLK_UP:
                                video_list->current = (video_list->current - 1 + video_list->count) % video_list->count;
                                need_switch = 1;
                                break;
                            case SDLK_DOWN:
                                video_list->current = (video_list->current + 1) % video_list->count;
                                need_switch = 1;
                                break;
                            case SDLK_SPACE:
                                // 空格键切换暂停状态
                                s->paused = !s->paused;
                                if (s->audioDevice) {
                                    SDL_PauseAudioDevice(s->audioDevice, s->paused);
                                }
                                // 立即重绘当前帧以显示暂停状态
                                render_video_frame(s, frame);
                                break;
                            case SDLK_LEFT: {
                                // 左键快退
                                Uint32 now = SDL_GetTicks();
                                if (now - s->last_seek_time > MIN_SEEK_INTERVAL) {
                                    int64_t current_pts = av_rescale(frame->pts, 
                                        AV_TIME_BASE * (int64_t)s->pFormatCtx->streams[s->videoStream]->time_base.num, 
                                        s->pFormatCtx->streams[s->videoStream]->time_base.den);
                                    s->seek_time = (current_pts / 1000) - SEEK_STEP;
                                    if (s->seek_time < 0) s->seek_time = 0;
                                }
                                break;
                            }
                            case SDLK_RIGHT: {
                                // 右键快进
                                Uint32 now = SDL_GetTicks();
                                if (now - s->last_seek_time > MIN_SEEK_INTERVAL) {
                                    int64_t current_pts = av_rescale(frame->pts, 
                                        AV_TIME_BASE * (int64_t)s->pFormatCtx->streams[s->videoStream]->time_base.num, 
                                        s->pFormatCtx->streams[s->videoStream]->time_base.den);
                                    s->seek_time = (current_pts / 1000) + SEEK_STEP;
                                    if (s->seek_time > s->pFormatCtx->duration / 1000) {
                                        s->seek_time = s->pFormatCtx->duration / 1000;
                                    }
                                }
                                break;
                            }
                            case SDLK_x:
                                if (ctrl_pressed) {
                                    // Ctrl+X 旋转视频
                                    s->rotation = (s->rotation + 90) % 360;
                                    // 更新显示宽高
                                    if (s->rotation == 90 || s->rotation == 270) {
                                        s->display_width = s->original_height;
                                        s->display_height = s->original_width;
                                    } else {
                                        s->display_width = s->original_width;
                                        s->display_height = s->original_height;
                                    }
                                    // 重新创建纹理
                                    if (s->texture) {
                                        SDL_DestroyTexture(s->texture);
                                    }
                                    s->texture = SDL_CreateTexture(s->renderer,
                                        SDL_PIXELFORMAT_YV12,
                                        SDL_TEXTUREACCESS_STREAMING,
                                        s->display_width, s->display_height);
                                    if (!s->texture) {
                                        fprintf(stderr, "无法重新创建纹理: %s\n", SDL_GetError());
                                    }
                                    // 重新创建图像转换上下文
                                    if (s->sws_ctx) {
                                        sws_freeContext(s->sws_ctx);
                                    }
                                    s->sws_ctx = sws_getContext(
                                        s->original_width,
                                        s->original_height,
                                        s->videoCodecCtx->pix_fmt,
                                        s->display_width, s->display_height,
                                        AV_PIX_FMT_YUV420P,
                                        SWS_BILINEAR,
                                        NULL, NULL, NULL);
                                    // 立即重绘当前帧
                                    render_video_frame(s, frame);
                                }
                                break;
                            case SDLK_n:
                                if (ctrl_pressed) {
                                    // Ctrl+N 重命名文件
                                    char old_name[PATH_MAX];
                                    char new_name[PATH_MAX];
                                    char basename[PATH_MAX];
                                    
                                    size_t old_name_len = strlen(video_list->filenames[video_list->current]);
                                    if (old_name_len >= PATH_MAX) old_name_len = PATH_MAX - 1;
                                    memcpy(old_name, video_list->filenames[video_list->current], old_name_len);
                                    old_name[old_name_len] = '\0';
                                    
                                    get_basename(old_name, basename);
                                    
                                    if (show_text_input_dialog("重命名文件", basename, new_name, PATH_MAX)) {
                                        // 添加文件后缀
                                        const char *ext = strrchr(old_name, '.');
                                        if (ext) {
                                            size_t ext_len = strlen(ext);
                                            size_t new_len = strlen(new_name);
                                            if (new_len + ext_len < PATH_MAX) {
                                                strncat(new_name, ext, PATH_MAX - new_len - 1);
                                            }
                                        }
                                        
                                        size_t new_name_len2 = strlen(new_name);
                                        if (new_name_len2 >= PATH_MAX) new_name_len2 = PATH_MAX - 1;
                                        memcpy(video_list->filenames[video_list->current], new_name, new_name_len2);
                                        video_list->filenames[video_list->current][new_name_len2] = '\0';
                                    }
                                }
                                break;
                            case SDLK_DELETE:
                                // 直接使用Delete键删除文件
                                {
                                    char filename[PATH_MAX];
                                    size_t filename_len = strlen(video_list->filenames[video_list->current]);
                                    if (filename_len >= PATH_MAX) filename_len = PATH_MAX - 1;
                                    memcpy(filename, video_list->filenames[video_list->current], filename_len);
                                    filename[filename_len] = '\0';
                                    
                                    if (delete_file(filename) == 0) {
                                        // 从列表中移除文件
                                        for (int i = video_list->current; i < video_list->count - 1; i++) {
                                            size_t move_len = strlen(video_list->filenames[i + 1]);
                                            if (move_len >= PATH_MAX) move_len = PATH_MAX - 1;
                                            memcpy(video_list->filenames[i], video_list->filenames[i + 1], move_len);
                                            video_list->filenames[i][move_len] = '\0';
                                        }
                                        video_list->count--;
                                        
                                        // 如果列表为空则退出
                                        if (video_list->count == 0) {
                                            quit = 1;
                                        } else {
                                            // 调整当前索引
                                            if (video_list->current >= video_list->count) {
                                                video_list->current = video_list->count - 1;
                                            }
                                            need_switch = 1;
                                        }
                                    }
                                }
                                break;
                            case SDLK_ESCAPE:
                                quit = 1;
                                break;
                        }
                    }
                }
                
                // 如果暂停，保持显示当前帧
                while (s->paused && !quit_flag && !quit && !need_switch && !need_reinit) {
                    SDL_Event event;
                    while (SDL_PollEvent(&event)) {
                        if (event.type == SDL_QUIT) {
                            quit = 1;
                            break;
                        } else if (event.type == SDL_KEYDOWN) {
                            // 检查Ctrl键是否按下
                            int ctrl_pressed = (event.key.keysym.mod & KMOD_CTRL) ? 1 : 0;
                            
                            switch (event.key.keysym.sym) {
                                case SDLK_UP:
                                    video_list->current = (video_list->current - 1 + video_list->count) % video_list->count;
                                    need_switch = 1;
                                    break;
                                case SDLK_DOWN:
                                    video_list->current = (video_list->current + 1) % video_list->count;
                                    need_switch = 1;
                                    break;
                                case SDLK_SPACE:
                                    // 空格键切换暂停状态
                                    s->paused = !s->paused;
                                    if (s->audioDevice) {
                                        SDL_PauseAudioDevice(s->audioDevice, s->paused);
                                    }
                                    // 立即重绘当前帧以显示暂停状态
                                    render_video_frame(s, frame);
                                    break;
                                case SDLK_LEFT: {
                                    // 左键快退
                                    Uint32 now = SDL_GetTicks();
                                    if (now - s->last_seek_time > MIN_SEEK_INTERVAL) {
                                        int64_t current_pts = av_rescale(frame->pts, 
                                            AV_TIME_BASE * (int64_t)s->pFormatCtx->streams[s->videoStream]->time_base.num, 
                                            s->pFormatCtx->streams[s->videoStream]->time_base.den);
                                        s->seek_time = (current_pts / 1000) - SEEK_STEP;
                                        if (s->seek_time < 0) s->seek_time = 0;
                                    }
                                    break;
                                }
                                case SDLK_RIGHT: {
                                    // 右键快进
                                    Uint32 now = SDL_GetTicks();
                                    if (now - s->last_seek_time > MIN_SEEK_INTERVAL) {
                                        int64_t current_pts = av_rescale(frame->pts, 
                                            AV_TIME_BASE * (int64_t)s->pFormatCtx->streams[s->videoStream]->time_base.num, 
                                            s->pFormatCtx->streams[s->videoStream]->time_base.den);
                                        s->seek_time = (current_pts / 1000) + SEEK_STEP;
                                        if (s->seek_time > s->pFormatCtx->duration / 1000) {
                                            s->seek_time = s->pFormatCtx->duration / 1000;
                                        }
                                    }
                                    break;
                                }
                                case SDLK_x:
                                    if (ctrl_pressed) {
                                        // Ctrl+X 旋转视频
                                        s->rotation = (s->rotation + 90) % 360;
                                        // 更新显示宽高
                                        if (s->rotation == 90 || s->rotation == 270) {
                                            s->display_width = s->original_height;
                                            s->display_height = s->original_width;
                                        } else {
                                            s->display_width = s->original_width;
                                            s->display_height = s->original_height;
                                        }
                                        // 重新创建纹理
                                        if (s->texture) {
                                            SDL_DestroyTexture(s->texture);
                                        }
                                        s->texture = SDL_CreateTexture(s->renderer,
                                            SDL_PIXELFORMAT_YV12,
                                            SDL_TEXTUREACCESS_STREAMING,
                                            s->display_width, s->display_height);
                                        if (!s->texture) {
                                            fprintf(stderr, "无法重新创建纹理: %s\n", SDL_GetError());
                                        }
                                        // 重新创建图像转换上下文
                                        if (s->sws_ctx) {
                                            sws_freeContext(s->sws_ctx);
                                        }
                                        s->sws_ctx = sws_getContext(
                                            s->original_width,
                                            s->original_height,
                                            s->videoCodecCtx->pix_fmt,
                                            s->display_width, s->display_height,
                                            AV_PIX_FMT_YUV420P,
                                            SWS_BILINEAR,
                                            NULL, NULL, NULL);
                                        // 立即重绘当前帧
                                        render_video_frame(s, frame);
                                    }
                                    break;
                                case SDLK_n:
                                    if (ctrl_pressed) {
                                        // Ctrl+N 重命名文件
                                        char old_name[PATH_MAX];
                                        char new_name[PATH_MAX];
                                        char basename[PATH_MAX];
                                        
                                        size_t old_name_len = strlen(video_list->filenames[video_list->current]);
                                        if (old_name_len >= PATH_MAX) old_name_len = PATH_MAX - 1;
                                        memcpy(old_name, video_list->filenames[video_list->current], old_name_len);
                                        old_name[old_name_len] = '\0';
                                        
                                        get_basename(old_name, basename);
                                        
                                        if (show_text_input_dialog("重命名文件", basename, new_name, PATH_MAX)) {
                                            // 添加文件后缀
                                            const char *ext = strrchr(old_name, '.');
                                            if (ext) {
                                                size_t ext_len = strlen(ext);
                                                size_t new_len = strlen(new_name);
                                                if (new_len + ext_len < PATH_MAX) {
                                                    strncat(new_name, ext, PATH_MAX - new_len - 1);
                                                }
                                            }
                                            
                                            size_t new_name_len2 = strlen(new_name);
                                            if (new_name_len2 >= PATH_MAX) new_name_len2 = PATH_MAX - 1;
                                            memcpy(video_list->filenames[video_list->current], new_name, new_name_len2);
                                            video_list->filenames[video_list->current][new_name_len2] = '\0';
                                        }
                                    }
                                    break;
                                case SDLK_DELETE:
                                    // 直接使用Delete键删除文件
                                    {
                                        char filename[PATH_MAX];
                                        size_t filename_len = strlen(video_list->filenames[video_list->current]);
                                        if (filename_len >= PATH_MAX) filename_len = PATH_MAX - 1;
                                        memcpy(filename, video_list->filenames[video_list->current], filename_len);
                                        filename[filename_len] = '\0';
                                        
                                        if (delete_file(filename) == 0) {
                                            // 从列表中移除文件
                                            for (int i = video_list->current; i < video_list->count - 1; i++) {
                                                size_t move_len = strlen(video_list->filenames[i + 1]);
                                                if (move_len >= PATH_MAX) move_len = PATH_MAX - 1;
                                                memcpy(video_list->filenames[i], video_list->filenames[i + 1], move_len);
                                                video_list->filenames[i][move_len] = '\0';
                                            }
                                            video_list->count--;
                                            
                                            // 如果列表为空则退出
                                            if (video_list->count == 0) {
                                                quit = 1;
                                            } else {
                                                // 调整当前索引
                                                if (video_list->current >= video_list->count) {
                                                    video_list->current = video_list->count - 1;
                                                }
                                                need_switch = 1;
                                            }
                                        }
                                    }
                                    break;
                                case SDLK_ESCAPE:
                                    quit = 1;
                                    break;
                            }
                        }
                    }
                    SDL_Delay(100); // 暂停时减少CPU使用率
                }
            }
        } else if (packet->stream_index == s->audioStream && !s->paused) {
            if (avcodec_send_packet(s->audioCodecCtx, packet) < 0) {
                fprintf(stderr, "发送音频数据包失败\n");
                av_packet_unref(packet);
                continue;
            }
            
            while (avcodec_receive_frame(s->audioCodecCtx, frame) == 0) {
                uint8_t *output = NULL;
                int out_samples = swr_get_out_samples(s->swr_ctx, frame->nb_samples);
                if (av_samples_alloc(&output, NULL, s->audioCodecCtx->ch_layout.nb_channels,
                    out_samples, AV_SAMPLE_FMT_S16, 0) < 0) {
                    fprintf(stderr, "无法分配音频样本缓冲区\n");
                    continue;
                }
                
                const uint8_t **in_data = (const uint8_t **)frame->data;
                out_samples = swr_convert(s->swr_ctx, 
                    &output, 
                    out_samples,
                    in_data,
                    frame->nb_samples);
                
                if (out_samples > 0) {
                    int data_size = out_samples * 
                        s->audioCodecCtx->ch_layout.nb_channels * 
                        av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
                    SDL_QueueAudio(s->audioDevice, output, data_size);
                }
                
                av_freep(&output);
            }
        }
        av_packet_unref(packet);
    }
    
    av_packet_free(&packet);
    av_frame_free(&frame);
    
    if (quit_flag || quit) return 0;
    if (need_switch) return 1;
    if (need_reinit) return 2;
    return -1;
}

int main(int argc, char *argv[]) {
    setlocale(LC_ALL, "");
    
    // 设置信号处理
    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);
    
    VideoList video_list = {0};
    
    // 处理命令行参数
    if (argc > 1) {
        size_t arg1_len = strlen(argv[1]);
        if (arg1_len >= PATH_MAX) arg1_len = PATH_MAX - 1;
        memcpy(video_list.filenames[0], argv[1], arg1_len);
        video_list.filenames[0][arg1_len] = '\0';
        video_list.count = 1;
        video_list.current = 0;
    } else {
        if (get_video_files(&video_list) < 0) {
            fprintf(stderr, "视频目录中没有找到视频文件\n");
            return -1;
        }
    }

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
        fprintf(stderr, "SDL初始化失败: %s\n", SDL_GetError());
        return -1;
    }
    
    av_log_set_level(AV_LOG_ERROR);
    
    PlayerState player = {0};
    
    // 主播放循环
    while (!quit_flag && video_list.current < video_list.count) {
        if (init_player(&player, video_list.filenames[video_list.current]) < 0) {
            fprintf(stderr, "初始化播放器失败: %s\n", video_list.filenames[video_list.current]);
            video_list.current++;
            continue;
        }
        
        int result = play_video(&player, &video_list);
        if (result == 0) break; // 用户退出
        else if (result == -1) video_list.current = (video_list.current + 1) % video_list.count;
    }
    
    // 清理资源
    if (player.window) SDL_DestroyWindow(player.window);
    if (player.renderer) SDL_DestroyRenderer(player.renderer);
    cleanup_player(&player);
    SDL_Quit();
    return 0;
}
